﻿using System;
using System.Reflection;

namespace Hadlow.Jobvertizer.HtmlHelpers
{
    public class TokenWalker
    {
        readonly object item;
        readonly string[] tokens;

        public TokenWalker(object item, string tokens)
        {
            this.item = item;
            this.tokens = tokens.Split('.');
        }

        public object GetValue()
        {
            if (tokens.Length == 1) return item;
            return GetValueAt(item, 1);
        }

        public object GetValueAt(object currentItem, int index)
        {
            if (currentItem == null)
            {
                return null;
            }

            PropertyInfo property = currentItem.GetType().GetProperty(tokens[index],
                BindingFlags.IgnoreCase
                | BindingFlags.Instance
                | BindingFlags.Public);
            if (property == null)
            {
                throw new ApplicationException(string.Format("Property '{0}' not found on type '{1}'",
                    tokens[index], currentItem.GetType().ToString()));
            }

            object value = property.GetValue(currentItem, null);

            if ((index + 1) == tokens.Length)
            {
                return value;
            }
            else
            {
                return GetValueAt(value, index + 1);
            }
        }
    }
}
